import { request } from "../../utils/index";
import {
  IMessage,
  IConversation,
  IGreetingStatus,
  MessageType,
} from "@/typings";

// 定义后端接口返回的数据结构
interface SendMsgRes {
  msg_id: string;
  createTime: number;
  greetingStatus?: IGreetingStatus;
}

interface GetMsgListRes {
  messages: IMessage[];
}

interface GetConversationListRes {
  conversations: IConversation[];
  total: number;
}

interface GetUnreadCountRes {
  totalUnreadCount: number;
  conversationUnreadCounts: {
    [conversation_id: string]: number;
  };
}

export const imApi = {
  /**
   * 发送消息 (单聊和系统通知，支持图片与文字两种类型)
   * 后端应该处理首次发送消息时自动创建会话的逻辑。
   */
  sendMsg: (
    to_uid: string,
    body: string,
    type: MessageType
  ): Promise<SendMsgRes> => {
    return request("im/sendMsg", { to_uid, body, type });
  },

  /**
   * 获取会话的消息列表
   */
  getMsgList: (
    conversation_id: string,
    maxCreateTime?: number,
    limit: number = 20
  ): Promise<GetMsgListRes> => {
    return request("im/getMsgList", { conversation_id, maxCreateTime, limit });
  },

  /**
   * 撤回消息
   */
  revokeMsg: (msg_id: string): Promise<any> => {
    return request("im/revokeMsg", { msg_id });
  },

  /**
   * 添加拉黑关系
   */
  addBlock: (block_uid: string): Promise<any> => {
    return request("im/addBlock", { block_uid });
  },

  /**
   * 移除拉黑关系
   */
  removeBlock: (block_uid: string): Promise<any> => {
    return request("im/removeBlock", { block_uid });
  },

  /**
   * 获取会话列表
   */
  getConversationList: (
    limit: number = 20,
    skip: number = 0,
    maxUpdateTime?: number
  ): Promise<GetConversationListRes> => {
    return request(
      "im/getConversationList",
      { limit, skip, maxUpdateTime },
      {
        showSuccessMessage: false,
      }
    );
  },

  /**
   * 获取当前用户所有会话的总未读数，以及每个会话的未读数
   */
  getUnreadCount: (): Promise<GetUnreadCountRes> => {
    return request("im/getUnreadCount");
  },

  /**
   * 清除当前用户所有会话的未读数
   */
  clearAllUnreadCount: (): Promise<any> => {
    return request("im/clearAllUnreadCount");
  },

  /**
   * 清除指定会话的未读数
   */
  clearConversationUnreadCount: (conversation_id: string): Promise<any> => {
    return request("im/clearConversationUnreadCount", { conversation_id });
  },
};
